package Overlapping;




import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class StringSet{

	private final String SPLIT_REGEX = "[^0-9a-zA-Z]+";

	private final Set<String> set = new HashSet<>();
	private final List<String> list = new ArrayList<>();
	private final String value;

	public StringSet() {
		value = null;
	}

	public StringSet(String value) {

		// do not lowercase, keep exact value, for author_id
		this.value = value;
		fill();
	}

	public void add(String x) {
		set.add(x);
	}

	public boolean contains(StringSet obj) {
		return set.containsAll(obj.set);
	}

	public boolean containsAtLeastOne(StringSet obj) {
		for (String i : obj.set)
			if (set.contains(i))
				return true;

		return false;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof StringSet))
			return false;
		StringSet other = (StringSet) obj;
		if (set == null) {
			if (other.set != null)
				return false;
		} else if (!set.equals(other.set))
			return false;
		return true;
	}

	public boolean equalsOrdered(StringSet o) {
		return list.equals(o.list);
	}

	private void fill() {
		String lower = value.trim().toLowerCase();
		String[] words = lower.split(SPLIT_REGEX);

		boolean all_digit = true;

		for (String s : words)
			if (!UMisc.isDigit(s)) {
				all_digit = false;
				break;
			}

		for (String s : words) {
			if (s.trim().isEmpty())
				continue;

			if (!all_digit && UMisc.isDigit(s))
				continue;

			set.add(s.trim());
			list.add(s.trim());
		}
	}

	public double getConfidence(StringSet ss) {
		assert contains(ss) || value.contains(ss.getValue()) : value + "<>"
				+ ss.value;
		return 1. * ss.size() / size();
	}


	public StringSet getKey() {
		return this;
	}


	public String getValue() {
		return value;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((set == null) ? 0 : set.hashCode());
		return result;
	}

	public boolean isEmpty() {
		return set.isEmpty();
	}

	public int size() {
		return set.size();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();

		for (String i : set)
			sb.append(String.format("%s::", i));

		return sb.toString();
	}
}
